package com.company.Thread.Concurrent;

import java.util.Date;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class lock2 {

    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for(int i=0; i<10;i++){
                data.A();
            }
        }).start();
        new Thread(()->{
            for(int i=0; i<10;i++){
                data.B();
            }
        }).start();
        new Thread(()->{
            for(int i=0; i<10;i++){
                data.C();
            }
        }).start();
    }
}

class Data{
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    private int n = 1;

    public void A(){
        lock.lock();
        try{
            while (n!=1){
                condition1.await();
            }
            System.out.println("I am A");
            n = 2;
            condition2.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void B(){
        lock.lock();
        try{
            while (n!=2){
                condition2.await();
            }
            System.out.println("I am B");
            n = 3;
            condition3.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void C(){
        lock.lock();
        try{
            while (n!=3){
                condition3.await();
            }
            System.out.println("I am C");
            n = 1;
            condition1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}